--local redis = require 'redis'
--local host = "111.231.201.108"
--local port = 16379
--client = redis.connect(host, port)
--client:auth('root')
--redis.call = function(cmd, ...)
--    return assert(loadstring('return client:'.. string.lower(cmd) ..'(...)'))(...)
--end

local rst = {}
local cmd = KEYS[1]
local statKey = KEYS[2]
local api = KEYS[3]
local costVal = tonumber(ARGV[1])
local cmdConst = { UPDATE = 'update', GET = 'query' }

local function queryStat(key)
    local rstList = redis.call('HGETALL', key)
    for i = 1, #rstList, 2 do
        local tmp = cjson.decode(rstList[i + 1])
        tmp.api = rstList[i]
        table.insert(rst, tmp)
    end
    redis.call('DEL', key)
end

local function stat(key, field, incrCost)
    local val = redis.call('HGET', key, field)
    local valTable = {}
    if val == nil or type(val) ~= 'string' then
        valTable = { cost = incrCost, frequency = 1 }
    else
        valTable = cjson.decode(val)
        valTable.frequency = valTable.frequency + 1
        local oldAvg = valTable.cost
        valTable.cost = tonumber(
                string.format('%.2f',
                        (incrCost - oldAvg) / valTable.frequency + oldAvg
                )
        )
    end
    redis.call('HSET', key, field, cjson.encode(valTable))
    rst = true
end

local function main()
    if cmd == cmdConst.UPDATE then
        stat(statKey, api, costVal)
    elseif cmd == cmdConst.GET then
        queryStat(statKey)
    end
end

main()
return cjson.encode({ rstList = rst })
